<template>
  <el-upload
    class="upload"
    :action="qiniuUploadUrl"
    :show-file-list="false"
    :before-upload="beforeUpload"
    :on-success="handleSuccess"
    :data="qiniuData"
    :multiple="multiple"
  >
    <slot />
    <div slot="tip" class="upload-tip">{{ tip }}</div>
  </el-upload>
</template>
<script>
const pinyin = require('chinese-to-pinyin');
import { testPicType, testPicSize } from '@/utils/img';
import { getToken } from '@/api/qiniu';
import { mapGetters } from 'vuex';
export default {
  name: 'ImageUpload',
  props: {
    size: {
      type: Number,
      required: true
    },
    imgname: {
      type: String,
      required: true
    },
    tip: {
      type: String,
      default: ''
    },
    multiple: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      qiniuData: {
        token: '',
        key: ''
      }
    };
  },
  computed: {
    ...mapGetters(['qiniuUploadUrl'])
  },
  methods: {
    async beforeUpload(file) {
      if (!testPicType(file) || !testPicSize(file, this.size, this.imgName)) return;
      const res = await getToken();
      this.qiniuData.token = res.data;
      this.qiniuData.key = `${file.uid}-${pinyin(file.name, { keepRest: true, firstCharacter: true, removeSpace: true })}`;
    },
    handleSuccess(res, file) {
      this.$emit('onSuccess', res.key);
    }
  }
};
</script>
<style lang="scss">
	.upload-tip{
		max-width: 360px;
    color: #838a9d;
    line-height: 22px;
	}
</style>
